﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Gollie.Mail;
using NLog;

namespace Gollie.Mail.Queue.Service
{
	public class Service : ServiceBase
	{
		private static readonly Logger logger = LogManager.GetCurrentClassLogger();

		private ServiceHost serviceHost = null;

		MainTask mainTask;

		private CancellationTokenSource cts;

		public Service()
		{
			ServiceName = "GollieMailQueue";
		}

		public static void Main()
		{
			ServiceBase.Run(new Service());
		}


		protected override void OnStart(string[] args)
		{
			try
			{
				if (serviceHost != null)
					serviceHost.Close();

				serviceHost = new ServiceHost(typeof(Gollie.Mail.Queue.Service.MailService));

				serviceHost.Open();

				this.cts = new CancellationTokenSource();

				Gollie.Service.ServiceHelper.SetCulture();

				this.mainTask = new MainTask(cts);// Task.Factory.StartNew(() => Run(this.cts.Token), this.cts.Token);
			}
			catch (Exception e)
			{
				logger.FatalException("Error", e);
				throw;
			}
		}

		protected override void OnStop()
		{
			logger.Info("Received stop request");

			if (serviceHost == null)
				return;

			if (this.mainTask == null)
				return;

			this.mainTask.Cancel();

			serviceHost.Close();
			serviceHost = null;

			logger.Info("Service stopped.");
		}

		protected override void OnShutdown()
		{
			logger.Info("Received shutdown request. Executing stop...");

			OnStop();
		}
	}
}
